import React, {Component} from 'react';

import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  TouchableHighlight,
  Platform,
} from 'react-native';

import { Icon } from 'react-native-elements';

import Sound from 'react-native-sound';
import {AudioRecorder, AudioUtils} from 'react-native-audio';

export default 

class RecordingView extends Component {

    state = {
      currentTime: 0.0,
      recording: false,
      paused: false,
      stoppedRecording: false,
      finished: false,
      hasPermission: undefined,
      duration: 0.0,
      soundtrackInfo:{}
    };

 prepareRecordingPath(audioPath){
    console.log("prepping the audio path", audioPath);
      AudioRecorder.prepareRecordingAtPath(audioPath, {
        SampleRate: 22050,
        Channels: 1,
        AudioQuality: "Low",
        AudioEncoding: "aac",
        AudioEncodingBitRate: 32000
      });
    }

  componentDidMount() {
    console.log("Recording view is mounting.");
      this._checkPermission().then((hasPermission) => {
        this.setState({ hasPermission });

        if (!hasPermission) return;

        dataManager.createSoundtrackInPlaylist(this.props.navigation.state.params.playlistId)
        .then((soundtrackInfo) => {

            console.log("Soundtrack info obtained", soundtrackInfo);
            this.setState({
              "soundtrackInfo": soundtrackInfo
            });
            this.prepareRecordingPath(soundtrackInfo["path"]);

        });

        // this.prepareRecordingPath();

        AudioRecorder.onProgress = (data) => {
          if(this.state.paused != true)
            this.setState({currentTime: Math.floor(data.currentTime)});
        };

         AudioRecorder.onFinished = (data) => {
          if (Platform.OS === 'ios') {
            this._finishRecording(data.status === "OK", data.audioFileURL);
          }
        };
      });
    }

    componentWillUnmount() {
      console.log("Recording view will unmount now.");
      if(typeof this.props.navigation.state.params.onDismiss == 'function')
      this.props.navigation.state.params.onDismiss();
    }

    _checkPermission() {
      if (Platform.OS !== 'android') {
        return Promise.resolve(true);
      }

      const rationale = {
        'title': 'Microphone Permission',
        'message': 'RiC Player needs access to your microphone so you can record audio.'
      };
    }

  _renderButton(title, onPress, active) {
      var style = (active) ? styles.activeButtonText : styles.buttonText;

      return (
        <TouchableHighlight style={styles.button} onPress={onPress}>
          <Text style={style}>
            {title}
          </Text>
        </TouchableHighlight>
      );
    }

    _renderPauseButton(onPress, active) {
      var style = (active) ? styles.activeButtonText : styles.buttonText;
      var title = this.state.paused ? "RESUME" : "PAUSE";
      return (
        <TouchableHighlight style={styles.button} onPress={onPress}>
          <Text style={style}>
            {title}
          </Text>
        </TouchableHighlight>
      );
    }

    componentWillUnmount() {
        //1. take the input value from the UI
        //2. update the duration of the recording: this.state.duration
        console.log("Writing the soundtrackInfo to disk.");
        dataManager.updateSoundtrackInfo(this.state.soundtrackInfo)
        .then(() => {
          console.log("Soundtrack info has been written to disk.");
        });


    }

    async _pause() {
      if (!this.state.recording) {
        console.warn('Can\'t pause, not recording!');
        return;
      }

      try {
        const filePath = await AudioRecorder.pauseRecording();
        this.setState({paused: true});
      } catch (error) {
        console.error(error);
      }
    }

    async _resume() {
      if (!this.state.paused) {
        console.warn('Can\'t resume, not paused!');
        return;
      }

      try {
        await AudioRecorder.resumeRecording();
        this.setState({paused: false});
      } catch (error) {
        console.error(error);
      }
    }

    async _stop() {
      if (!this.state.recording) {
        console.warn('Can\'t stop, not recording!');
        return;
      }

      this.setState({stoppedRecording: true, recording: false, paused: true});
    }

    async _play() {
      if (this.state.recording) {
        await this._stop();
      }

      // These timeouts are a hacky workaround for some issues with react-native-sound.
      // See https://github.com/zmxv/react-native-sound/issues/89.
      setTimeout(() => {
        var sound = new Sound(this.state.audioPath, '', (error) => {
          if (error) {
            console.log('failed to load the sound', error);
          }
        });

        setTimeout(() => {
          sound.play((success) => {
            if (success) {
              console.log('successfully finished playing');
            } else {
              console.log('playback failed due to audio decoding errors');
            }
          });
        }, 100);
      }, 100);
    }

    _record() {
      if (this.state.recording) {
        console.warn('Already recording!');
        return;
      }

      // initialize the soundtrack
      dataManager.createSoundtrackInPlaylist(this.props.navigation.state.params.playlistId)
        .then(async (soundtrackInfo) => {

            console.log("Soundtrack info obtained", soundtrackInfo);
            this.prepareRecordingPath(soundtrackInfo["path"]);


            this.setState({recording: true, paused: false});

            try {
              const filePath = await AudioRecorder.startRecording();
            } catch (error) {
              console.error(error);
            }

        });

    }

    _finishRecording(didSucceed, filePath) {
      this.state.soundtrackInfo.duration = this.state.currentTime;
      this.setState({ finished: didSucceed, soundtrackInfo: this.state.soundtrackInfo });

      console.log(`Finished recording of duration ${this.state.currentTime} seconds at path: ${filePath}`);
    }

    render() {

      return (
        <View style={styles.container}>
          
          <View style={{flex:2, backgroundColor: 'black'}} >
          </View>
 
           
<Text style= {styles.progressText}>{this.state.currentTime}s
           </Text>

          <View style={styles.record} >
          <Icon 
          reverse
          name='record-rec'
          type='material-community'
          size={35}
          color='#f50' 
          onPress={this._renderButton(() => {this._record()}, this.state.recording )} />
          </View>

          <View style={styles.controls}>
          <Icon
            reverse
            name='play-circle'
            type='material-community'
            onPress={this._renderButton(() => {this._play()} )} />
       
            <Icon
            reverse
            name='stop-circle'
            type='material-community'
            onPress={this._renderButton(() => {this._stop()} )} />
            <Icon
            reverse
            name='pause-circle'
            type='material-community'
            onPress={this._renderPauseButton(() => {this.state.paused ? this._resume() : this._pause()} )} />
           
           </View>
          </View>
        
       
      );
    }
  }

  var styles = StyleSheet.create({
    container: {
      flex: 1,
      borderRadius: 4,
      borderWidth: 0.5,
      backgroundColor: "#3C3C3C",
      flexDirection: "column",
    },
     progressText: {
      paddingTop: 5,
      fontSize: 20,
      color: "#6FACD6",
      textAlign:'center',
    },
    record: {
      justifyContent: 'center',
      alignSelf: 'center',
      flex: 1,
    },
    controls: {
      justifyContent: 'center',
      alignItems: 'flex-end',
      flex: 1,
      flexDirection: 'row',
      bottom: 0,
    },
    button: {
      padding: 40
    },
    disabledButtonText: {
      color: '#96F5F6'
    },
    buttonText: {
      fontSize: 30,
      color: "#ADADAD"
    },
    activeButtonText: {
      fontSize: 20,
      color: "#B81F00"
    }

  });
